﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Hr;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.Hr;
using ESOL.WinUI.MasterData;
using ESOL.Common.Schema;

namespace ESOL.WinUI.Hr
{
    public partial class frmMaintainEmployee : BaseForm.frmBaseDialogyMaintainForm
    {
        #region Variable
        public MstPersonEntity SelectedPerson { get; set; }
        private HrEmployeeEntity mSelectedEmployee;
        private HrAgentEntity mSelectedAgent;
        #endregion

        #region Constructor
        public frmMaintainEmployee()
        {
            InitializeComponent();
            if (SelectedPerson == null)
            {
                SelectedPerson = new MstPersonEntity();
                SelectedPerson.PersonId = Guid.NewGuid().ToString();
            }
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbGender, "GENDER", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "PS", false);
            cmbStatus.SelectedValue = "PS07";
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbEducation, "EDU", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPoliticalLandscape, "PLS", true);
            UICommon.UICommonFunctions.BindComboboxByEnum(cmbIsMarrid, typeof(IsMarrid), typeof(int), true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbTitle, "ZC", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPositionType, "PST", false);
        }
        private void SetEmployeeFields()
        {
            if (mSelectedEmployee == null)
            {
                return;
            }
            txtIdNo.Text = mSelectedEmployee.IdNo;
            if (mSelectedEmployee.JoinDate.ToString("yyyy-MM-dd") != "1900-01-01" &&
                mSelectedEmployee.JoinDate.ToString("yyyy-MM-dd") != "0001-01-01")
            {
                dtpJoinDate.EditValue = mSelectedEmployee.JoinDate;
            }
            if (mSelectedEmployee.LeaveDate.ToString("yyyy-MM-dd") != "1900-01-01" &&
                mSelectedEmployee.LeaveDate.ToString("yyyy-MM-dd") != "0001-01-01")
            {
                dtpLeaveDate.EditValue = mSelectedEmployee.LeaveDate;
            }
            txtBasicSalary.Text = mSelectedEmployee.BasicSalary.ToString("#0.00");
            txtSocialFundAmount.Text = mSelectedEmployee.SocialFundAmount.ToString("#0.00");
            cmbPoliticalLandscape.SetSelectedValue(mSelectedEmployee.PoliticalLandscape);
            cmbEducation.SetSelectedValue(mSelectedEmployee.Education);
            txtMajor.Text = mSelectedEmployee.Major;
            txtMinor.Text = mSelectedEmployee.Minor;
            txtOfficePhone.Text = mSelectedEmployee.OfficePhone;
            if (mSelectedEmployee.ContractEndDate.ToString("yyyy-MM-dd") != "1900-01-01" &&
                mSelectedEmployee.ContractEndDate.ToString("yyyy-MM-dd") != "0001-01-01")
            {
                dtpContractEndDate.EditValue = mSelectedEmployee.ContractEndDate;
            }
            txtContractCode.Text = mSelectedEmployee.ContractCode;
            cmbIsMarrid.SetSelectedValue(mSelectedEmployee.IsMarried);
            txtNativeAddress.Text = mSelectedEmployee.NativeAddress;
            cmbTitle.SetSelectedValue(mSelectedEmployee.Title);
            txtSocialSecurityNo.Text = mSelectedEmployee.SocialSecurityNo;
     
            if (mSelectedEmployee.IsSocialSecurity == 1)
            {
                cboxIsSocialSecurity.Checked = true;
            }
            else
            {
                cboxIsSocialSecurity.Checked = false;
            }
            //DownloadPhoto(mSelectedEmployee.PersonImage);
        }

        private void SetAgentFields()
        {
            if (mSelectedAgent == null)
            {
                txtAgentPerson.Tag = null;
                txtAgentPerson.Text = "";
                txtAgentMobile.Text = "";
                txtAgentHomePhone.Text = "";
                txtAgentOfficePhone.Text = "";
            }
            else
            {
                MstPersonEntity agentPerson = MstPersonBs.GetMstPersonByID(mSelectedAgent.AgentId);
                HrEmployeeEntity agentEmployee = HrEmployeeBs.GetHrEmployeeByPersonId(mSelectedAgent.AgentId);
                txtAgentPerson.Tag = agentPerson;
                if (agentPerson != null)
                {
                    txtAgentPerson.Text = agentPerson.NameCn;
                    txtAgentMobile.Text = agentPerson.Mobile;
                    txtAgentHomePhone.Text = agentPerson.Telephone;
                }
                else
                {
                    txtAgentPerson.Text = "";
                    txtAgentMobile.Text = "";
                    txtAgentHomePhone.Text = "";
                }
                if (agentEmployee != null)
                {
                    txtAgentOfficePhone.Text = agentEmployee.OfficePhone;
                }
                else
                {
                    txtAgentOfficePhone.Text = "";
                }
            }
        }

        private void SetFields()
        {
            if (SelectedPerson == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(SelectedPerson.DepartmentId) == false)
            {
                MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(SelectedPerson.DepartmentId);
                txtDepartment.Text = department.DepartmentName;
                txtDepartment.Tag = department;
            }
            txtPersonCode.Text = SelectedPerson.PersonCode;
            txtPersonNameCn.Text = SelectedPerson.NameCn;
            txtPersonNameCn.Text = SelectedPerson.NameEn;
            cmbGender.SetSelectedValue(SelectedPerson.Gender);
            cmbStatus.SetSelectedValue(SelectedPerson.Status);
            txtEmail.Text = SelectedPerson.Email;
            txtTelephone.Text = SelectedPerson.Telephone;
            txtMobile.Text = SelectedPerson.Mobile;
            if (string.IsNullOrEmpty(SelectedPerson.Birthday) == false)
            {
                dtpBirthday.EditValue = Convert.ToDateTime(SelectedPerson.Birthday);
            }
            txtCountry.Text = SelectedPerson.Country;
            txtProvince.Text = SelectedPerson.Province;
            txtCity.Text = SelectedPerson.City;
            txtAddress.Text = SelectedPerson.Address;
            txtLastModifiedDate.Text = SelectedPerson.LastModifiedDate.ToString("yyyy-MM-dd hh:mm:ss");
            txtLastModifiedBy.Text = "";
            txtUpload.Text = SelectedPerson.Attachment ;
            if (string.IsNullOrEmpty(SelectedPerson.LastModifiedBy) == false)
            {
                MstPersonEntity p = MstPersonBs.GetMstPersonByID(SelectedPerson.LastModifiedBy);
                if (p != null)
                {
                    txtLastModifiedBy.Text = p.NameCn;
                }
            }
            mSelectedEmployee = HrEmployeeBs.GetHrEmployeeByPersonId(SelectedPerson.PersonId);
            SetEmployeeFields();
            mSelectedAgent = HrAgentBs.GetHrAgentByPerson(SelectedPerson.PersonId);
            SetAgentFields();
            BindPositionGrid();
        }

        private void SetEntity()
        {
            SelectedPerson.DepartmentId = null;
            if (txtDepartment.Tag != null && txtDepartment.Tag.GetType() == typeof(MstDepartmentEntity))
            {
                MstDepartmentEntity department = (MstDepartmentEntity)txtDepartment.Tag;
                SelectedPerson.DepartmentId = department.DepartmentId;
            }
            SelectedPerson.PositionId = null;
            if (!txtPersonCode.Text.Equals(""))
            {
                SelectedPerson.PersonCode = txtPersonCode.Text;
            }
            //SelectedPerson.PersonCode = txtPersonCode.Text;
            SelectedPerson.NameCn = txtPersonNameCn.Text;
            SelectedPerson.NameEn = txtPersonNameCn.Text;
            SelectedPerson.Gender = CommonFunctions.ToString(cmbGender.SelectedValue);
            SelectedPerson.Status = CommonFunctions.ToString(cmbStatus.SelectedValue);
            SelectedPerson.Email = txtEmail.Text;
            SelectedPerson.Telephone = txtTelephone.Text;
            SelectedPerson.Mobile = txtMobile.Text;
            if (dtpBirthday.EditValue!=null)
            {
                SelectedPerson.Birthday = ((DateTime)dtpBirthday.EditValue).ToString("yyyy-MM-dd");
            }
            SelectedPerson.Country = txtCountry.Text;
            SelectedPerson.Province = txtProvince.Text;
            SelectedPerson.City = txtCity.Text;
            SelectedPerson.Address = txtAddress.Text;
            SelectedPerson.LastModifiedDate = DateTime.Now;
            txtLastModifiedBy.Text = "";
            SelectedPerson.Attachment  = txtUpload.Text;
            SelectedPerson.LastModifiedBy = CommonParameter.CurrentUser.PersonId;

            //Employee
            if (mSelectedEmployee == null)
            {
                mSelectedEmployee = new HrEmployeeEntity();
            }
            mSelectedEmployee.PersonId = SelectedPerson.PersonId;
            mSelectedEmployee.IdNo = txtIdNo.Text;
 
            if (dtpJoinDate.EditValue!=null)
            {
                mSelectedEmployee.JoinDate = (DateTime)dtpJoinDate.EditValue;
            }
            if (dtpLeaveDate.EditValue!=null)
            {
                mSelectedEmployee.LeaveDate = (DateTime)dtpLeaveDate.EditValue;
            }
            mSelectedEmployee.BasicSalary = CommonFunctions.ToDecimal(txtBasicSalary.Text);
            mSelectedEmployee.SocialFundAmount = CommonFunctions.ToDecimal(txtSocialFundAmount.Text);
            if (cmbPoliticalLandscape.SelectedValue != null && cmbPoliticalLandscape.SelectedValue.ToString().Trim() != "")
            {
                mSelectedEmployee.PoliticalLandscape = cmbPoliticalLandscape.SelectedValue.ToString();
            }
            if (cmbEducation.SelectedValue != null && cmbEducation.SelectedValue.ToString().Trim() != "")
            {
                mSelectedEmployee.Education = cmbEducation.SelectedValue.ToString();
            }
            mSelectedEmployee.Major = txtMajor.Text;
            mSelectedEmployee.Minor = txtMinor.Text;
            mSelectedEmployee.OfficePhone = txtOfficePhone.Text;
            if (dtpContractEndDate.EditValue!=null)
            {
                mSelectedEmployee.ContractEndDate = (DateTime)dtpContractEndDate.EditValue;
            }
            mSelectedEmployee.ContractCode = txtContractCode.Text;
            mSelectedEmployee.IsMarried = CommonFunctions.ToInt32(cmbIsMarrid.SelectedValue);
            mSelectedEmployee.NativeAddress = txtNativeAddress.Text;
            if (cmbTitle.SelectedValue != null)
            {
                mSelectedEmployee.Title = cmbTitle.SelectedValue.ToString();
            }
            else
            {
                mSelectedEmployee.Title = null;
            }
            mSelectedEmployee.SocialSecurityNo = txtSocialSecurityNo.Text;
            if (cboxIsSocialSecurity.Checked)
            {
                mSelectedEmployee.IsSocialSecurity = 1;
            }
            else
            {
                mSelectedEmployee.IsSocialSecurity = 0;
            }

            //Agent
            if (txtAgentPerson.Tag != null && txtAgentPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                MstPersonEntity agent = (MstPersonEntity)txtAgentPerson.Tag;
                mSelectedAgent = new HrAgentEntity();
                mSelectedAgent.PersonId = SelectedPerson.PersonId;
                mSelectedAgent.AgentId = agent.PersonId;
            }
            else
            {
                mSelectedAgent = null; 
            }
        }

        private bool UploadPhoto()
        {
            try
            {
                if (pboxPersonImage.Tag != null && pboxPersonImage.Tag.GetType() == typeof(string) && pboxPersonImage.BackgroundImage != null)
                {
                    Image image = (Image)pboxPersonImage.Image;
                    string fileName = (string)pboxPersonImage.Tag;
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        mSelectedEmployee.PersonImage = SelectedPerson.PersonCode + "." + CommonFunctions.GetFileExtension(fileName);
                        string path = service.GetEmployeePhotoPath();
                        byte[] bytes = CommonFunctions.FileToByte(fileName);
                        string errMsg = "";
                        bool result = service.UploadFileNew(bytes, path + "\\" + mSelectedEmployee.PersonImage, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        result = HrEmployeeBs.UpdateHrEmployee(mSelectedEmployee);
                        return result;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void DownloadPhoto(string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }
                using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                {
                    string path = service.GetEmployeePhotoPath();
                    string errMsg = "";
                    byte[] bytes = service.DownloadFileNew(path + "\\" + fileName, out errMsg);
                    if (string.IsNullOrEmpty(errMsg) == false)
                    {
                        MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (bytes != null)
                    {
                        pboxPersonImage.BackgroundImage = CommonFunctions.byteArrayToImage(bytes);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private bool UploadAttached(string FileName)
        {
            try
            {
                if (string.IsNullOrEmpty(FileName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        //SelectedPerson.AccessoryPathway = SelectedPerson.PersonCode + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + CommonFunctions.GetFileExtension(FileName);
                        string path = service.GetEmployeefilePath();
                        byte[] bytes = CommonFunctions.FileToByte(FileName);
                        string errMsg = "";

                        bool result = service.UploadFileNew(bytes, path + "\\" + CommonFunctions.GetFilePrefix(FileName), out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }

                        result = HrEmployeeBs.UpdateHrEmployee(mSelectedEmployee);

                        return result;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        private bool DownloadAttached(string FilefullName)
        {
            try
            {
                if (string.IsNullOrEmpty(FilefullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        string errMsg = "";
                        string path = service.GetEmployeefilePath();
                        byte[] bytes = service.DownloadFileNew(path + "\\" + CommonFunctions.GetFilePrefix(SelectedPerson .Attachment ), out errMsg);
                       
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        Image image = CommonFunctions.byteArrayToImage(bytes);
                        image.Save(FilefullName);
                        image.Dispose();
                        return true;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtDepartment.Text))
            {
                MessageBox.Show("所属部门不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtPersonCode.Text))
            {
                MessageBox.Show("员工工号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtPersonNameCn.Text))
            {
                MessageBox.Show("员工姓名不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpBirthday.EditValue == null)
            {
                MessageBox.Show("员工生日不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtIdNo.Text))
            {
                MessageBox.Show("身份证号码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpJoinDate.EditValue == null)
            {
                MessageBox.Show("入职日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpContractEndDate.EditValue == null)
            {
                MessageBox.Show("合同到期日不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtContractCode.Text))
            {
                MessageBox.Show("合同编号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtMobile.Text))
            {
                MessageBox.Show("手机号码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gridView1.RowCount==0)
            {
                MessageBox.Show("员工职位不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtProvince .Text ))
            {
                MessageBox.Show("所属省份不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCity .Text ))
            {
                MessageBox.Show("所属城市不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtBasicSalary .Text ))
            {
                MessageBox.Show("基本工资不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtMajor .Text ))
            {
                MessageBox.Show("专业不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbEducation.SelectedValue == null || string.IsNullOrEmpty(cmbEducation.SelectedValue.ToString ()))
            {
                MessageBox.Show("学历不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbPoliticalLandscape.SelectedValue == null || string.IsNullOrEmpty(cmbPoliticalLandscape.SelectedValue.ToString ()))
            {
                MessageBox.Show("政治面貌不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbIsMarrid.SelectedValue == null || string.IsNullOrEmpty(cmbIsMarrid.SelectedValue.ToString ()))
            {
                MessageBox.Show("婚姻状况不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private List<HrPersonPositionEntity> GetPersonPosition()
        {
            List<HrPersonPositionEntity> list = new List<HrPersonPositionEntity>();
            DataTable dt = gvPosition.DataSource as DataTable;
            foreach(DataRow dr in dt.Rows)
            {
                HrPersonPositionEntity entity = new HrPersonPositionEntity(dr);
                entity.PersonId = SelectedPerson.PersonId;
                if (entity != null)
                {
                    list.Add(entity);
                }
            }
            return list;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                SetEntity();
                if (ThisActionType == ActionType.New)
                {
                    bool isSuccessful = MstPersonBs.SavePerson(true, SelectedPerson, mSelectedEmployee, mSelectedAgent, GetPersonPosition());
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    bool isSuccessful = MstPersonBs.SavePerson(false, SelectedPerson, mSelectedEmployee, mSelectedAgent, GetPersonPosition());
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                //UploadPhoto();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void ResetFieldsEnable()
        {
            if (ThisActionType == ActionType.View)
            {
                btnUploadPhoto.Enabled = false;
            }
            else
            {
                btnUploadPhoto.Enabled = true;
            }
            if (ThisActionType == ActionType.New)
            {
                dtpJoinDate.Enabled = true;
                dtpContractEndDate.Enabled = true;
                dtpLeaveDate.Enabled = true;
                txtBasicSalary.Properties.ReadOnly = false;
            }
            else
            {
                dtpJoinDate.Enabled = false;
                dtpContractEndDate.Enabled = false;
                dtpLeaveDate.Enabled = false;
                txtBasicSalary.Properties.ReadOnly = true;
            }
        }

        private void BindPositionGrid()
        {
            string personId = "";
            if (SelectedPerson != null)
            {
                personId = SelectedPerson.PersonId;
            }
            DataSet ds = HrPersonPositionBs.GetPersonPositionById(personId);
            if (ds != null && ds.Tables.Count > 0)
            {
                gvPosition.DataSource = ds.Tables[0];
            }
            else
            {
                gvPosition.DataSource = null;
            }
        }
        #endregion

        #region Event
        private void frmMaintianEmployee_Load(object sender, EventArgs e)
        {
            BindComboBox();
            SetFields();
            ResetFieldsEnable();
            BindPositionGrid();
            if (ThisActionType != ActionType.New)
            {
                txtBasicSalary.Properties.PasswordChar = '*';
            }
            else
            {
                gvPosition.ContextMenuStrip = cmsActions;
            }
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtDepartment_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainDepartmentQuery frm = new frmMaintainDepartmentQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedDepartment != null)
            {
                txtDepartment.Text = frm.SelectedDepartment.DepartmentName;
                txtDepartment.Tag = frm.SelectedDepartment;
            }
            else
            {
                txtDepartment.Text = "";
                txtDepartment.Tag = null;
            }
        }

        private void txtAgentPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                mSelectedAgent = new HrAgentEntity();
                mSelectedAgent.PersonId = SelectedPerson.PersonId;
                mSelectedAgent.AgentId = frm.SelectedPerson.PersonId;
                SetAgentFields();
            }
            else
            {
                mSelectedAgent = null;
                SetAgentFields();
            }
        }

        private void txtProvince_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainAreaQuery frm = new frmMaintainAreaQuery(true, txtProvince.Text);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedArea != null)
            {
                txtProvince.Text = frm.SelectedArea.AreaName;
                txtProvince.Tag = frm.SelectedArea;
            }
            else
            {
                txtProvince.Text = "";
                txtProvince.Tag = null;
            }
        }

        private void txtCity_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainAreaQuery frm = new frmMaintainAreaQuery();
            if (txtProvince.Tag != null && txtProvince.Tag.GetType() == typeof(MstAreaEntity))
            {
                frm = new frmMaintainAreaQuery((MstAreaEntity)txtProvince.Tag);
            }
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedArea != null)
            {
                txtCity.Text = frm.SelectedArea.AreaName;
                txtCity.Tag = frm.SelectedArea;
            }
            else
            {
                txtCity.Text = "";
                txtCity.Tag = null;
            }
        }

        private void smiAdd_Click(object sender, EventArgs e)
        {
            DataTable dt = gvPosition.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dr["PERSON_ID"] = SelectedPerson.PersonId;
            dt.Rows.Add(dt.NewRow());
        }

        private void smiDelete_Click(object sender, EventArgs e)
        {
            if (drPositionSelected != null)
            {
                DataTable dt = gvPosition.DataSource as DataTable;
                dt.Rows.Remove(drPositionSelected);
            }
        }

        private void colPosition_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPositionQuery frm = new frmMaintainPositionQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPosition != null)
            {
                drPositionSelected["POSITION_ID"] = frm.SelectedPosition.PositionId;
                drPositionSelected["POSITION_NAME"] = frm.SelectedPosition.PositionName;
            }
            else
            {
                drPositionSelected["POSITION_ID"] = DBNull.Value;
                drPositionSelected["POSITION_NAME"] = DBNull.Value;
            }
        }

        private void colSuperior_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                drPositionSelected["SUPERVISOR_NAME"] = frm.SelectedPerson.NameCn;
                drPositionSelected["SUPERVISOR"] = frm.SelectedPerson.PersonId;
            }
            else
            {
                drPositionSelected["SUPERVISOR_NAME"] = DBNull.Value;
                drPositionSelected["SUPERVISOR"] = DBNull.Value;
            }
        }

        private DataRow drPositionSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
                return;
            DataTable dt = (DataTable)gvPosition.DataSource;
            if (dt.Rows.Count == 0)
                return;
            drPositionSelected = dt.Rows[e.FocusedRowHandle];
        }

        private void btnUploadPhoto_Click(object sender, EventArgs e)
        {
            try
            {
                if (ThisActionType != ActionType.Modify)
                {
                    MessageBox.Show("用户必须先保存才能上传照片!","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    return;
                }
                OpenFileDialog fd = new OpenFileDialog();
                fd.Filter = "PNG格式|*.png|JPG格式|*.jpg";
                fd.Multiselect = false;
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    Image image = Bitmap.FromFile(fd.FileName);
                    if (image.Height > 128 || image.Width > 128)
                    {
                        MessageBox.Show("照片过大，像数请不要超过128*128 !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    pboxPersonImage.BackgroundImage = image;
                    pboxPersonImage.Tag = fd.FileName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
       

        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (ThisActionType != ActionType.Modify)
                {
                    MessageBox.Show("用户必须先保存才能上传附件!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                OpenFileDialog fd = new OpenFileDialog();
                fd.Filter = "JPG文件|*.jpg|PNG文件|*.png";
                fd.Multiselect = false;
                if (fd.ShowDialog() == DialogResult.OK)
                {

                    Cursor = Cursors.WaitCursor;
                    bool result = UploadAttached(fd.FileName);
                    Cursor = Cursors.Default;
                    if (result)
                    {
                        txtUpload.Text = CommonFunctions.GetFilePrefix(fd.FileName);
                        MessageBox.Show("上传成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            txtDownload.Text = txtUpload.Text;
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("没有可下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SaveFileDialog fd = new SaveFileDialog();
            fd.FileName = txtDownload.Text;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = DownloadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                { MessageBox.Show("下载成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); }

            }
        }

        //private void smiAdd_Click(object sender, EventArgs e)
        //{
        //    if (gvPosition.DataSource == null)
        //    {
        //        BindPositionGrid();
        //    }
        //    if (gvPosition.DataSource == null)
        //    {
        //        return;
        //    }
        //    DataTable dt = (DataTable)gvPosition.DataSource;
        //    frmGetPosition frm = new frmGetPosition();
        //    if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //    {
        //        DataRow dr = dt.NewRow();
        //        dr["POSITION_TYPE"] = frm.PositionType;
        //        dr["POSITION_NAME"] = frm.SelectedPosition.PositionName;
        //        dr["PERSON_ID"] = SelectedPerson.PersonId;
        //        dr["POSITION_ID"] = frm.SelectedPosition.PositionId;
        //        if (frm.SelectedPerson != null)
        //        {
        //            dr["SUPERVISOR_NAME"] = frm.SelectedPerson.NameCn;
        //            dr["SUPERVISOR"] = frm.SelectedPerson.PersonId;
        //        }
        //        dt.Rows.Add(dr);
        //    }
        //}

        //private void smiDelete_Click(object sender, EventArgs e)
        //{
        //    if (gvPosition.SelectedRows.Count > 0)
        //    {
        //        gvPosition.Rows.Remove(gvPosition.SelectedRows[0]);
        //    }
        //}

        //private void smiModify_Click(object sender, EventArgs e)
        //{
        //    if (gvPosition.SelectedRows.Count > 0)
        //    {
        //        string positionId = "";
        //        string personId = "";
        //        string positionType = "";
        //        if (gvPosition.SelectedRows[0].Cells["colPOSITION_ID"].Value != null)
        //        {
        //            positionId = gvPosition.SelectedRows[0].Cells["colPOSITION_ID"].Value.ToString();
        //        }
        //        if (gvPosition.SelectedRows[0].Cells["colSUPERVISOR"].Value != null)
        //        {
        //            personId = gvPosition.SelectedRows[0].Cells["colSUPERVISOR"].Value.ToString();
        //        }
        //        if (gvPosition.SelectedRows[0].Cells["colPOSITION_TYPE"].Value != null)
        //        {
        //            positionType = gvPosition.SelectedRows[0].Cells["colPOSITION_TYPE"].Value.ToString();
        //        }
        //        frmGetPosition frm = new frmGetPosition(positionId, personId, positionType);
        //        if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //        {
        //            gvPosition.SelectedRows[0].Cells["colPOSITION_TYPE"].Value = frm.PositionType;
        //            gvPosition.SelectedRows[0].Cells["colPOSITION_NAME"].Value = frm.SelectedPosition.PositionName;
        //            gvPosition.SelectedRows[0].Cells["colPERSON_ID"].Value = SelectedPerson.PersonId;
        //            gvPosition.SelectedRows[0].Cells["colPOSITION_ID"].Value = frm.SelectedPosition.PositionId;
        //            if (frm.SelectedPerson != null)
        //            {
        //                gvPosition.SelectedRows[0].Cells["colSUPERVISOR_NAME"].Value = frm.SelectedPerson.NameCn;
        //                gvPosition.SelectedRows[0].Cells["colSUPERVISOR"].Value = frm.SelectedPerson.PersonId;
        //            }
        //        }
        //    }
        //}
        #endregion

    }
}
